<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\LihuaOrder;
use app\common\model\LihuaOrderGoods;
use app\common\model\LihuaOrderLogistics;
use app\common\model\LihuaOrderPayment;
use app\common\model\LihuaOrderActivity; //订单活动表
use app\common\model\general\LihuaCity;
use app\common\model\goods\LihuaGoods;
use fast\Http;
use think\Db;
use think\Log;

/**
 * 订单处理
 */
class Lhorder extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 抓取城市订单列表
     *
     * @ApiMethod   (POST)
     * @ApiReturn   */
    public function lists_test()
    {
        // $city_id = (int)$this->request->request('city_id');
        // if (!$city_id) $this->error('参数错误');

        $sn_arr = [
            '2004704802415876',
            '2004215392465172',
            '2004196932419227',
            '2004988712532721',
            '2004164672629427',
            '2004920902736027',
            '2005315180481337',
            '2005071820798289',
            '2005608120825834',
            '2005069120829646'
        ];

        $list = LihuaOrder::all(function ($query) use ($sn_arr) {
            $query->where(['sn'=> ['IN', $sn_arr]])
                ->field('goods,confirm_time,store_time,rider_time,finish_time,cancel_time,create_time,update_time', true)
                ->limit(10);
        });
		//支付方式:1=支付宝支付,2=微信支付,3=丽华钱包,4=货到付款,5=贵宾卡,6=微支付YL,7=云闪付
		$pay_type_text = ['', '支付宝', '微支付', '丽华钱包', '货到付款', '贵宾卡', '微支付YL', '云闪付'];
        $data = [];
        if ($list) {
            $order_ids = array_column($list, 'id');
            $order_sns = array_column($list, 'sn');
            $goodsList = LihuaOrderGoods::ordersGoodsList($order_ids);
            $actList = LihuaOrderActivity::ordersActList($order_sns);
            $res = LihuaOrderPayment::whereIn('order_id', $order_ids)
                ->field('order_id,pay_name,pay_money')->select();
            $payList = [];
            foreach ($res as $k => $v) {
                $payList[$v['order_id']][] = [
                    'pay_name'  => $v['pay_name'],
                    'pay_money' => $v['pay_money'],
                ];
            }
            foreach ($list as $k => $v) {
				$payText = '';
				if($v['pay_type']!=4){
					$payText = '('.$pay_type_text[$v['pay_type']].')';

                    if( $v['pay_type']==1 || $v['pay_type']==2 || $v['pay_type']==6 || $v['pay_type']==7 ){
                        if( $v['wallet_given_fee']>0 || $v['wallet_money_pay']>0 ){
                            $payText = $payText.'(丽华钱包)';

                            
                        }
                    }

				}
				if($v['enough_fee']> 0){
					$payText = $payText . '(满减-'.$v['enough_fee'].'元)';
				}
				if($v['bonus_fee']> 0){
				    $payText = $payText . '(红包-'.$v['bonus_fee'].'元)';
                }

                //如果有参加某活动
                if(isset($actList[$v['sn']])){
                    foreach($actList[$v['sn']] as $k2 => $v2) {
                        if($v2['type'] == 0){
                            $payText = $payText . '(' . $v2['name'] . '-' . $v2['discount'] . '元)';
                        }
                        if($v2['type'] == 1){
                            $payText = $payText . '(' . $v2['name'] . '-' . $v2['discount'] . '元)';
                        }
                    }
                }

                // $v['original_amount'] - $v['order_amount']
                if($v['city_id']==1 || $v['city_id']==2){
                    $discount_string = '';
                    if($v['pay_type']!=4){
                        $discount_string = '('.$pay_type_text[$v['pay_type']].')';
                        if( $v['pay_type']==1 || $v['pay_type']==2 || $v['pay_type']==6 || $v['pay_type']==7 ){
                            if( $v['wallet_given_fee']>0 || $v['wallet_money_pay']>0 ){
                                $discount_string = $discount_string.'(丽华钱包)';
                                //上海地区如果使用丽华钱包不允许开发票
                                if($v['city_id']==2 && $v['wallet_money_pay']>0){
                                    $list[$k]['invo_title'] = ''; 
                                    $list[$k]['invo_taxno'] = ''; 
                                    $list[$k]['invo_type'] = 0; 
                                }
                            }
                        }
                    }
                    $discount_num = bcsub($v['original_amount'], $v['order_amount'], 2);
                    if($discount_num>0){
                        $discount_string = $discount_string . "(促-" . $discount_num . '元)';
                    }
                    $list[$k]['address'] = $discount_string.$v['address'];
                }else{
                    $list[$k]['address'] = $payText.$v['address'];
                }

            }

            // foreach ($goodsList as $k2 => $v2) {
            //     $goodsList[$k2]['name'] = trim($v2['name']);
            // }


            $data = [
                'orderList' => $list,
                'goodsList' => $goodsList,
                'payList'   => $payList,
                'actList'   => $actList,
            ];
        }
        $this->success('OK', $data);
    }

    /**
     * 抓取城市订单列表
     *
     * @ApiMethod   (POST)
     * @ApiReturn   */
    public function lists()
    {
        $city_id = (int)$this->request->request('city_id');
        if (!$city_id) $this->error('参数错误');

        $list = LihuaOrder::all(function ($query) use ($city_id) {
            $query->where(['city_id' => $city_id, 'status' => 2, 'office_id'=> 0])
                ->field('goods,confirm_time,store_time,rider_time,finish_time,cancel_time,create_time,update_time', true)
                ->limit(30);
        });
		//支付方式:1=支付宝支付,2=微信支付,3=丽华钱包,4=货到付款,5=贵宾卡,6=微支付YL,7=云闪付
		$pay_type_text = ['', '支付宝', '微支付', '丽华钱包', '货到付款', '贵宾卡', '微支付YL', '云闪付'];
        $data = [];
        if ($list) {
            $order_ids = array_column($list, 'id');
            $order_sns = array_column($list, 'sn');
            $goodsList = LihuaOrderGoods::ordersGoodsList($order_ids);
            $actList = LihuaOrderActivity::ordersActList($order_sns);
            $res = LihuaOrderPayment::whereIn('order_id', $order_ids)
                ->field('order_id,pay_name,pay_money')->select();
            $payList = [];
            foreach ($res as $k => $v) {
                $payList[$v['order_id']][] = [
                    'pay_name'  => $v['pay_name'],
                    'pay_money' => $v['pay_money'],
                ];
            }
            foreach ($list as $k => $v) {
				$payText = '';
				if($v['pay_type']!=4){
					$payText = '('.$pay_type_text[$v['pay_type']].')';
                    if( $v['pay_type']==1 || $v['pay_type']==2 || $v['pay_type']==6 || $v['pay_type']==7 ){
                        if( $v['wallet_given_fee']>0 || $v['wallet_money_pay']>0 ){
                            $payText = $payText.'(丽华钱包)';
                        }
                    }
				}
				if($v['enough_fee']> 0){
					$payText = $payText . '(满减-'.$v['enough_fee'].'元)';
				}
				if($v['bonus_fee']> 0){
				    $payText = $payText . '(红包-'.$v['bonus_fee'].'元)';
                }

                //如果有参加某活动
                if(isset($actList[$v['sn']])){
                    foreach($actList[$v['sn']] as $k2 => $v2) {
                        if($v2['type'] == 0){
                            $payText = $payText . '(' . $v2['name'] . '-' . $v2['discount'] . '元)';
                        }
                        if($v2['type'] == 1){
                            $payText = $payText . '(' . $v2['name'] . '-' . $v2['discount'] . '元)';
                        }
                    }
                }

                // $v['original_amount'] - $v['order_amount']
                if($v['city_id']==1 || $v['city_id']==2){
                    $discount_string = '';
                    if($v['pay_type']!=4){
                        if($v['city_id']==1 &&$v['pay_type']==3){
                            $discount_string = '('.$pay_type_text[$v['pay_type']].'-'.$v['wallet_money_pay'].')';
                        }else{
                            $discount_string = '('.$pay_type_text[$v['pay_type']].')';
                        }                        
                        if( $v['pay_type']==1 || $v['pay_type']==2 || $v['pay_type']==6 || $v['pay_type']==7 ){
                            if( $v['wallet_given_fee']>0 || $v['wallet_money_pay']>0 ){
                                if($v['city_id']==1){
                                    $discount_string = $discount_string.'(丽华钱包-'.$v['wallet_money_pay'].')';
                                }else{
                                    $discount_string = $discount_string.'(丽华钱包)';
                                }
                                //上海地区如果使用丽华钱包不允许开发票
                                if($v['city_id']==2 && $v['wallet_money_pay']>0){
                                    $list[$k]['invo_title'] = ''; 
                                    $list[$k]['invo_taxno'] = ''; 
                                    $list[$k]['invo_type'] = 0; 
                                }
                            }
                        }
                    }
                    $discount_num = bcsub($v['original_amount'], $v['order_amount'], 2);
                    if($discount_num>0){
                        $discount_string = $discount_string . "(促-" . $discount_num . '元)';
                    }
                    $list[$k]['address'] = $discount_string.$v['address'];
                }else{
                    $list[$k]['address'] = $payText.$v['address'];
                }

            }

            // foreach ($goodsList as $k2 => $v2) {
            //     $goodsList[$k2]['name'] = trim($v2['name']);
            // }


            $data = [
                'orderList' => $list,
                'goodsList' => $goodsList,
                'payList'   => $payList,
                'actList'   => $actList,
            ];
        }
        $this->success('OK', $data);
    }

    /**
     * 更新订单状态
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="sn", type="string", required=true, description="订单号")
     * @ApiParams   (name="status", type="int", required=true, description="订单状态")
     * @ApiParams   (name="des", type="string", required=true, description="状态描述")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1570765630","data":{}})
     */
    public function updatestatus()
    {
        //状态：0=取消订单，3=确认订单，4=分配门店，5=骑手配送，6=订单完成
        $sn     = $this->request->request('sn');
        $status = $this->request->request('status');
        $des    = $this->request->request('des', '');
        if (!$sn || !in_array($status, [0,3,4,5,6])) $this->error('参数错误');

        $row = LihuaOrder::getBySn($sn);
        if (!$row) $this->error($sn . ' 订单不存在');
        switch ($status) {
            case 3:
                if ($row->status > 2) $this->error($sn . '订单状态错误');
                if ($row->status == 0) $this->error($sn . '订单已经取消');
                $row->status = 3;
                $row->confirm_time = date('Y-m-d H:i:s');
                break;

            case 4:
                if ($row->status > 3) $this->error($sn . '订单状态错误');
                if ($row->status == 0) $this->error($sn . '订单已经取消');
                $row->status = 4;
                $row->store_time = date('Y-m-d H:i:s');
                break;

            case 5:
                if ($row->status > 4) $this->error($sn . '订单状态错误');
                if ($row->status == 0) $this->error($sn . '订单已经取消');
                $row->status = 5;
                $row->rider_time = date('Y-m-d H:i:s');
                break;

            case 6:
                if ($row->status > 5) $this->error($sn . '订单状态错误');
                if ($row->status == 0) $this->error($sn . '订单已经取消');
                $row->status = 6;
                $row->finish_time = date('Y-m-d H:i:s');
                break;

            case 0:
                $row->status = 0;
                $row->cancel_time = date('Y-m-d H:i:s');
                break;
        }
        $row->save();
        if ($des) {
            LihuaOrderLogistics::create([
                'order_id' => $row['id'],
                'order_sn' => $sn,
                'des'      => $des,
                'status'   => $row->status,
            ]);
        }

        $this->success('OK');
    }

    /**
     *  拷贝老官网菜单及分类到新系统
     *  $sn = $this->request->request('sn');
     *  $status = $this->request->request('status');
     * **/
    public function copyData()
    {
        $city_id     = $this->request->request('city_id');
        $city_name   = $this->request->request('city_name');
        $res = Http::post('https://api.lihua.com/index/Good/copyOldGoodData_all', ['cityname' => $city_name, 'current_date' => date('Y-m-d')]);
        if ($res) {
            $arr = json_decode($res, true);
            if (!is_null($arr)) {
                if ($arr['status'] == 1) {
                    $cateList = $arr['data']['cate_list'];//分类列表
                    $goodList = $arr['data']['good_list'];//商品列表
                    $cateCnt  = count($cateList);
                    foreach ($cateList as $k => $v) {
                        $data = [
                            'old_id'  => $v['id'],
                            'city_id' => $city_id,
                            'name'    => $v['title'],
                            'weigh'   => bcsub(100, $v['sort'], 0),
                            'status'  => 1,
                        ];
                        $cateCnt--;
                        try {
                            $row = Db::name('lihua_category')->where('old_id', $v['id'])->find();
                            if ($row) {
                                Db::name('lihua_category')->where('id', $row['id'])->update($data);
                            } else {
                                Db::name('lihua_category')->insert($data);
                            }
                        } catch (\Exception $e) {
                            // $this->log($e->getMessage());
                            Log::record('[ copyData1 ]' . $e->getMessage(), 'info');
                        }
                    }

                    $cates = Db::name('lihua_category')->where('city_id', $city_id)->column('old_id,id');
                    $goodList = array_reverse($goodList);
                    foreach ($goodList as $k => $v) {
                        $data = [
                            'old_id'        => $v['id'],
                            'city_id'       => $city_id,
                            'category_id'   => isset($cates[$v['category_id']]) ? $cates[$v['category_id']] : 0,
                            'name'          => $v['name'],
                            'short_name'    => $v['short'],
                            'description'   => $v['desc'],
                            'pic'           => $v['pic'],
                            'type'          => $v['is_alone_sale'] == 1 ? 1 : 2,
                            'price'         => round($v['promote_price'], 2)>0 ?  $v['promote_price'] : $v['price'], //商品价格
							'original_price'=> $v['price'],  //商品原价
                            'box_fee'       => $v['box_fee'],
                            'is_alone_sale' => $v['is_alone_sale'] == 2 ? 0 : 1,
                            'sale_start'    => $v['sale_start_date'],
                            'sale_end'      => $v['sale_end_date'],
                            'limit_num'     => $v['limit_num'],
                            'at_least'      => $v['at_least'],
                            'status'        => 1,
                        ];
                        try {
                            $row = LihuaGoods::where('old_id', $v['id'])->field('id')->find();
                            if ($row) {
                                LihuaGoods::where('id', $row['id'])->update($data);
                            } else {
                                LihuaGoods::create($data);
                            }
                        } catch (\Exception $e) {
                            $this->error($e->getMessage());
                        }
                    }
                    $this->success($arr['message']);
                } else {
                    $this->error($arr['message']);
                }
            } else {
                $this->error('[ 源数据JSON ]' . json_last_error_msg());
            }
            
        } else {
            $this->success('[ 未获取到 ]' . $city_name . '商品数据');
        }
    }

}